package com.gcloud.mesh.isc.ims.controller;

import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.config.IscConfig;
import org.jeecg.modules.system.entity.SysLog;
import org.jeecg.modules.system.entity.SysLogBackup;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserDepart;
import org.jeecg.modules.system.mapper.SysLogMapper;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gcloud.mesh.alert.service.HistoryService;
import com.gcloud.mesh.analysis.service.impl.SubhealthThresholdService;
import com.gcloud.mesh.asset.service.IAssetService;
import com.gcloud.mesh.asset.service.ICloudResourceService;
import com.gcloud.mesh.dcs.dao.DataCleanDao;
import com.gcloud.mesh.dcs.service.AppService;
import com.gcloud.mesh.dcs.service.SchedulerService;
import com.gcloud.mesh.header.enums.SubhealthDeviceType;
import com.gcloud.mesh.header.msg.analysis.CountAlertsMsg;
import com.gcloud.mesh.header.msg.dcs.PageAppMsg;
import com.gcloud.mesh.header.vo.asset.CountDeviceVo;
import com.gcloud.mesh.redis.MockRedis;
import com.sgcc.isc.core.orm.identity.User;
import com.sgcc.isc.service.adapter.factory.AdapterFactory;
import com.sgcc.isc.service.adapter.helper.IRunMonitorService;

@Service
public class IscImsController {

	@Autowired
	private MockRedis<Object> redis;

	@Autowired
	private AppService appService;

	@Autowired
	private HistoryService historyService;

	@Autowired
	private SchedulerService schedulerService;

	@Autowired
	private DataCleanDao dao;

	@Autowired
	private IAssetService assetService;

	@Autowired
	private SubhealthThresholdService subhealthThresholdService;

	@Autowired
	private ICloudResourceService cloudResourceService;

	@Autowired
	private SysLogMapper sysLogMapper;
	
	@Autowired
	private SysUserMapper sysUserMapper;

	private static final SimpleDateFormat monitorSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	IRunMonitorService runMonitorService = (IRunMonitorService) AdapterFactory.getInstance("runMonitorService");

	// @Resource
	// RedisSessionDAO sessionDAO;

	public String createXml(List<String> apis, String code) throws NoSuchMethodException, SecurityException,
			IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		Document document = DocumentHelper.createDocument();
		Element r = document.addElement("return");

		Element corporationCode = r.addElement("CorporationCode");
		corporationCode.addAttribute("id", code);
		for (String apiMethod : apis) {
			// 执行每个调用方法
			String methodName = IscImsMethodType.getMethodByName(apiMethod);
			Element api = corporationCode.addElement("api");
			api.addAttribute("name", apiMethod);

			Method method = this.getClass().getMethod(methodName, null);
			String res = (String) method.invoke(this, null);

			Element value = api.addElement("value");
			value.setText(res);
		}
		Element status = r.addElement("status");
		status.setText("success");
		Element message = r.addElement("message");
		message.setText("执行的结果成功");

		return "" + trans(document) + "";
	}

	private String trans(Document document) {
		OutputFormat oFormat = OutputFormat.createPrettyPrint();
		oFormat.setEncoding("gb2312");
		StringWriter sWriter = new StringWriter();
		XMLWriter xWriter = new XMLWriter(sWriter, oFormat);
		xWriter.setEscapeText(false);
		try {
			xWriter.write(document); // 为document
			xWriter.flush();
			xWriter.close();
		} catch (IOException e) {
			System.err.println("转换xml异常！");
		}
		String xml = sWriter.toString();
		return xml;
	}

	public String businessUserRegNum() throws Exception {
		int res = sysUserMapper.selectCount(new QueryWrapper<SysUser>());
		return res + "";
		
	//	return runMonitorService.getBusinessUserRegNum(IscConfig.getIscAppId(), null, null);
	}

	public String businessSystemOnlineNum() {

		List<Object> users = redis.getUserToken();
		for (Object user : users) {
			String token = user.toString();
			String userName = JwtUtil.getUsername(token);
		}

		// Collection<Session> sessions = sessionDAO.getActiveSessions();
		// for (Session session : sessions) {
		// Object attribute =
		// session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
		// if (attribute == null) {
		// continue;
		// }
		// User user = (User) ((SimplePrincipalCollection)
		// attribute).getPrimaryPrincipal();
		// if (user == null) {
		// continue;
		// }
		// }

		return users.size() + "";
	}

	public String businessDayLoginNum() throws Exception {

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		Date time = calendar.getTime();
		
		
		List<SysLogBackup> res = sysLogMapper.getSystemRollByTime(monitorSdf.format(time), CommonConstant.OPERATE_TYPE_LOGIN);
		return res.size() + "";
		
		//return runMonitorService.getBusinessDayLoginNum(IscConfig.getIscAppId(), null, null);
	}

	public String businessVisitCount() throws Exception {
		List<SysLog> res = sysLogMapper.selectList(new QueryWrapper<SysLog>().eq("operate_type", CommonConstant.OPERATE_TYPE_LOGIN));
		return res.size() + "";
		
		//return runMonitorService.getBusinessVisitCount(IscConfig.getIscAppId(), null, null);
	}

	public String businessSystemSessionNum() {
		List<Object> users = redis.getUserToken();
		for (Object user : users) {
			String token = user.toString();
			String userName = JwtUtil.getUsername(token);
		}
		return users.size() + "";
	}

	public String businessSystemResponseTime() {
		Long startTime = new Date().getTime();
		appService.page(new PageAppMsg());
		assetService.pageDevice(1, 999, null, null, "");
		Long endTime = new Date().getTime();
		return (endTime - startTime) + "";
	}

	public String businessSystemRunningTime() {
		Long now = new Date().getTime();

		Long time = now - (Long) redis.getBeginTime();
		long res = (time / 1000) ;
		return res + "";
	}

	public String businessDataTableSpace() {
		return dao.dbSize();
	}

	public String businessSystemDBTime() {
		Long startTime = new Date().getTime();
		appService.page(new PageAppMsg());
		assetService.pageDevice(1, 999, null, null, "");
		Long endTime = new Date().getTime();
		return (endTime - startTime) + "";
	}

	public String businessSystemLoginRoll() throws Exception {
		String res = "";
		
//		List<SysUser> users = sysUserMapper.selectList(new QueryWrapper<SysUser>());
//		for(SysUser user : users) {
//			res = res + user.getUsername() + "\n";
//		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		Date time = calendar.getTime();
		
		
		List<SysLogBackup> resb = sysLogMapper.getSystemRollByTime(monitorSdf.format(time), CommonConstant.OPERATE_TYPE_LOGIN);
		for(SysLogBackup backup : resb) {
			res = res + backup.getUsername() + "\n";
		}
		//return res.size() + "";
//		List<User> users = runMonitorService.getBusinessSystemLoginRoll(IscConfig.getIscAppId(), null, null);
//		for (User user : users) {
//			res = res + user.getUserName() + "\n";
//		}
		return res;
	}

	public String businessSystemOnlineRoll() {
		String res = "";
		List<Object> users = redis.getUserToken();
		for (Object user : users) {
			String token = user.toString();
			String userName = JwtUtil.getUsername(token);
			res = res + userName + "\n";
		}
		return res;
	}

	public String businessSystemIaasDeviceNum() {
		CountDeviceVo vo = assetService.countDevice(null);
		return vo.getTotal() - vo.getServerNum() - vo.getSwitcherNum() + "";
	}

	public String businessSystemServerNum() {
		CountDeviceVo vo = assetService.countDevice(null);
		return vo.getServerNum() + "";
	}

	public String businessSystemSwitcherNum() {
		CountDeviceVo vo = assetService.countDevice(null);
		return vo.getSwitcherNum() + "";
	}

	public String businessSystemAlertNum() {
		int c = historyService.count(null);
		return c + "";
	}

	public String businessSystemAppNum() {
		int c = appService.count();
		return c + "";
	}

	public String businessSystemSchedulerJobNum() {
		int c = schedulerService.count(null);
		return c + "";
	}

	public String businessSystemSubhealthAlertNum() {
		CountAlertsMsg alert = new CountAlertsMsg();
		alert.setDeviceType(SubhealthDeviceType.AIR.getName());
		int c1 = subhealthThresholdService.countAlerts(alert);
		CountAlertsMsg alert2 = new CountAlertsMsg();
		alert2.setDeviceType(SubhealthDeviceType.DATACENTER.getName());
		int c2 = subhealthThresholdService.countAlerts(alert2);
		CountAlertsMsg alert3 = new CountAlertsMsg();
		alert3.setDeviceType(SubhealthDeviceType.UPS.getName());
		int c3 = subhealthThresholdService.countAlerts(alert3);
		return c1+c2+c3 + "";
	}

	public String businessSystemDatacenterNum() {
		int c = assetService.countDatacenter();
		return c + "";
	}

	public String businessSystemCloudResourceVmNum() {
		int c = cloudResourceService.count(0);
		return c + "";
	}

	public String businessSystemCloudResourceContainerNum() {
		int c = cloudResourceService.count(1);
		return c + "";
	}
}
